<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="用户id" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户id...."
          clearable
          style="width: 200px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="导航模块" prop="tagIds">
        <el-select
          v-model="queryParams.tagIds"
          placeholder="请选择导航模块...."
          clearable
          style="width: 200px"
        >
          <el-option
            v-for="dict in navRoutersArray"
            :key="dict.value"
            :label="dict.remark"
            :value="dict.dictCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="关键词" prop="keyWord">
        <el-input
          v-model="queryParams.keyWord"
          placeholder=""
          clearable
          style="width: 200px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="审核状态" prop="state">
        <el-select
          v-model="queryParams.state"
          placeholder="请选择导航模块...."
          clearable
          style="width: 200px"
        >
          <el-option
            v-for="dict in stateOptions"
            :key="dict.label"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="删除状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder=""
          clearable
          style="width: 200px"
        >
          <el-option
            v-for="dict in statusOptions"
            :key="dict.label"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:dict:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-refresh"
          size="mini"
          @click="handleRefreshCache"
          v-hasPermi="['system:dict:remove']"
          >刷新缓存</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="typeList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="帖子标题" align="center" prop="courseTitle">
        <template slot-scope="scope">
          <router-link
            :to="{
              name: targetRoute,
              query: {
                id: scope.row.id,
                title: scope.row.title,
              },
            }"
            target="_blank"
            style="
              color: rgb(0, 195, 255);
              text-decoration: underline 1px dashed rgb(0, 195, 255);
            "
            >{{ scope.row.title }}</router-link
          >
        </template>
      </el-table-column>
      <el-table-column label="用户名" align="center" prop="userName" />
      <el-table-column label="用户ID" align="center" prop="createUser" />
      <el-table-column label="帖子ID" align="center" prop="id" width="200px" />
      <el-table-column label="审核状态" align="center" prop="state">
        <template slot-scope="scope">
          <div
            class="change-btn"
            @click="chengState(scope.row.state, scope.row)"
          >
            {{ scope.row.state }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="删除状态" align="center" prop="state">
        <template slot-scope="scope">
          <div
            class="change-btn"
            @click="changeStatus(scope.row.status, scope.row)"
          >
            {{ scope.row.status ? "已删除" : "正常" }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="收藏量" align="center" prop="collectTotal" />
      <el-table-column label="评论量" align="center" prop="commentTotal" />
      <el-table-column label="点赞量" align="center" prop="likeTotal" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        fixed="right"
      >
        <template slot-scope="scope">
          <!-- <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['system:dict:edit']"
              >修改</el-button> -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:dict:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="帖子标题" prop="title">
          <el-input v-model="form.title" placeholder="" :readonly="true" />
        </el-form-item>
        <el-form-item label="帖子ID" prop="id">
          <el-input v-model="form.id" placeholder="" :readonly="true" />
        </el-form-item>
        <el-form-item label="通过审核" prop="state">
          <el-radio-group v-model="form.state">
            <el-radio
              v-for="dict in stateOptionsDialog"
              :key="dict.value"
              :label="dict.label"
              :disabled="form.state === 'WAIT' ? false : true"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="删除状态" prop="recommendStatus">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.label"
              :label="dict.value"
              >{{ dict.remark }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <!-- <el-form-item label="备注" prop="remarkData">
            <el-input
              v-model="form.remarkData"
              type="textarea"
              placeholder="审核反馈备注...."
            ></el-input>
          </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listType,
  getType,
  delType,
  addType,
  updateType,
  refreshCache,
} from "@/api/system/dict/type";
import { delPost } from "@/api/szpt/getPostList";
import { getDicts } from "@/api/system/dict/data";
import { getPostListBackstage, changeStateStatus } from "@/api/szpt/backstage";

export default {
  name: "Dict",
  dicts: ["sys_normal_disable"],
  data() {
    return {
      //目标路由
      targetRoute: "szSource",
      // 导航模块
      navRoutersArray: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 字典表格数据
      typeList: [],
      // 审核状态
      passStatus: [],
      // 推荐状态
      recommendStatusArray: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      stateOptions: [
        {
          label: "PASS",
          value: "PASS",
        },
        {
          label: "REJECT",
          value: "REJECT",
        },
        {
          label: "WAIT",
          value: "WAIT",
        },
      ],
      stateOptionsDialog: [
        {
          label: "PASS",
          value: "PASS",
        },
        {
          label: "REJECT",
          value: "REJECT",
        },
      ],
      statusOptions: [
        {
          label: "NORMAL",
          value: "0",
          remark: "正常",
        },
        {
          label: "DELETE",
          value: "1",
          remark: "已删除",
        },
      ],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        tagIds: "",
        userId: "",
        sortType: "TIME_DESC",
        keyWord: "",
        state: "",
        status: "",
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        dictName: [
          { required: true, message: "字典名称不能为空", trigger: "blur" },
        ],
        dictType: [
          { required: true, message: "字典类型不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    getDicts("szpt_nav_status").then((resp) => {
      this.navRoutersArray = resp.data;
      // this.queryParams.tagIds = this.navRoutersArray[0].dictCode
      this.getList();
    });
    getDicts("szpt_recommend_status").then((resp) => {
      resp.data.forEach((item) => {
        this.recommendStatusArray.push(item);
      });
    });
    getDicts("szpt_post_status").then((resp) => {
      resp.data.forEach((item) => {
        this.passStatus.push(item);
      });
    });
  },
  methods: {
    // 改变审核状态
    chengState(state, row) {
      if (state === "WAIT") {
        this.open = true;
        this.reset();
        const dictId = row.id;
        this.open = true;
        this.form = { ...row };
        this.form.status = this.form.status.toString();
      } else {
        this.$message.warning("审核状态已改变不可更改！");
      }
    },
    changeStatus(status, row) {
      if (status) {
        this.open = true;
        this.reset();
        const dictId = row.id;
        this.open = true;
        this.form = { ...row };
        this.form.status = this.form.status.toString();
      } else {
        this.$message.warning("状态暂时无法改变！");
      }
    },
    /** 格式化数据格式*/
    fmtDataList(dataDetail) {
      const typeListData = [];
      dataDetail.forEach((dataItem) => {
        const userDTO = dataItem.userDTO;
        const countDTO = dataItem.countDTO;
        const dataDTO = dataItem.data;
        // const content =JSON.parse(dataItem.data.content)
        const dataList = {
          ...userDTO.data,
          ...countDTO,
          ...dataDTO,
          //  ...content,
          //  发布状态默认不推荐
          ...{ recommendStatus: "0" },
        };
        typeListData.push(dataList);
      });
      this.loading = false;
      return typeListData;
    },
    /** 查询字典类型列表 */
    getList() {
      this.loading = true;
      getPostListBackstage(this.queryParams).then((resp) => {
        if (resp.data.pageInfo) {
          this.typeList = this.fmtDataList(resp.data.pageInfo.list);
          this.total = resp.data.pageInfo.total;
        } else {
          this.typeList = [];
          this.loading = false;
          this.total = 0;
        }
      });
      this.$nextTick(() => {
        this.$forceUpdate();
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加字典类型";
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.dictId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const dictId = row.id;
      this.open = true;
      this.form = { ...row };
      this.form.status = this.form.status.toString();
    },
    /** 提交按钮 */
    submitForm: function () {
      changeStateStatus(this.form)
        .then((resp) => {
          if (resp.code == 200) {
            this.$message.success("状态更新成功!");
            this.open = false;
          }
        })
        .catch((err) => {
          this.$message.error("状态更改失败!");
          console.log(err);
        });
      this.getList();
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      if (row.status) {
        this.$message.warning("已删除！不可重复操作");
      } else {
        const dictIds = row.id;
        this.$modal
          .confirm('是否确认删除帖子ID为"' + dictIds + '"的数据项？')
          .then(function () {
            return delPost(dictIds);
          })
          .then(() => {
            this.getList();
            this.$modal.msgSuccess("删除成功");
          })
          .catch((err) => {
            console.log("err", err);
          });
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/dict/type/export",
        {
          ...this.queryParams,
        },
        `type_${new Date().getTime()}.xlsx`
      );
    },
    /** 刷新缓存按钮操作 */
    handleRefreshCache() {
      refreshCache().then(() => {
        this.$modal.msgSuccess("刷新成功");
        this.$store.dispatch("dict/cleanDict");
      });
    },
  },
  mounted() {},
};
</script>
<style lang="scss" scoped>
.change-btn {
  cursor: pointer;
  color: rgb(0, 195, 255);
}
</style>
